var express = require('express');
var router = express.Router();
var UserModel = require('../model/User');
var md5 = require('md5');

router.get('/api/intercept', function(req, res, next) {
  var result = {
    code: 1,
    message: "已登录"
  }
  if(req.session == null || req.session.username == null){
    result.code = 0;
  }
    res.json(result);
});

router.get('/api/signout', function(req, res, next) {

  req.session.username = null;
  res.send("登出");
});

router.post('/api/register', function(req, res, next) {
  console.log(req.body.username)
  var username = req.body.username;
  var pwd = req.body.pwd;
  var result = {
    code: 1,
    message: "注册成功"
  };
  console.log(111)
  UserModel.find({username:username},function(err,docs){
    console.log(222)
    if(docs.length > 0){
      result.code = -109;
      result.message = "此用户名已被注册";
      res.json(result);
      return;
    }
    var um = new UserModel();
    um.username = username;
    um.pwd = md5(pwd);
    um.save(function(err){
      if(err){
        result.code = -100;
        result.message = "注册失败";
        res.send("注册失败");
      }
      req.session.username = username;
      res.json(result);
    })
  })
});

router.post('/api/login', function(req, res, next) {
  var username = req.body.username;
  var pwd = req.body.pwd;
  var result = {
    code: 1,
    message: "登录成功"
  };
  UserModel.find({username: username,pwd: md5(pwd)},function(err,docs){
    if(docs.length == 0) {
      result.code = -101;
      result.message = "您的账号或密码错误，请重新登录!"
    }else{
      req.session.username = username;
    }
    res.json(result);
  })
});

module.exports = router;
